<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../libs/bootstrap.css">
    <style>

        tbody img{width:40px;}

    </style>
</head>
<body>
    <h2>这是购物车<small><a href="../search/index.html">继续选购</a></small></h2>
    <table class="table mt-5">
        <thead>
            <tr>
                <th>全选：<input type="checkbox" class="allCheck"></th>
                <th>图片</th>
                <th style="width:400px;">名称</th>
                <th style="width:50px;">数量</th>
                <th>售价</th>
                <th>总价</th>
                <th>删除</th>
            </tr>
        </thead>
        <tbody>
            <!-- <tr>
                <td>1</td>
                <td>1</td>
                <td>1</td>
                <td>1</td>
                <td><input type="number"></td>
                <td>1</td>
                <td><span class="btn btn-warning">删除</span></td>
            </tr> -->
        </tbody>
        <tfoot>
            <tr>
                <td colspan="3" align="right">总数量：</td>
                <td class="allNum">0</td>
                <td align="right">合计：</td>
                <td class="allPrice">0</td>
            </tr>
        </tfoot>
    </table>
</body>
<script src="../libs/jquery.js"></script>
<script>
    class Cart{
        constructor(){
            this.cont = $("tbody");
            this.url = "../data/pro.json";
            this.load();
            this.addEvent();
        }
        addEvent(){
            const that = this;
            this.cont.on("click",".del",function(eve){
                that.id = $(this).parent().parent().attr("data-id");
                $(this).parent().parent().remove();
                that.setData(function(i){
                    that.proMsg.splice(i,1);
                });
            })
            this.cont.on("input",".set",function(eve){
                that.id = $(this).parent().parent().attr("data-id");

                let sumEle = $(this).parent().next().next();
                let priceEle = $(this).parent().next();
                sumEle.html($(this).val() * priceEle.html());

                that.setData((i)=>{
                    that.proMsg[i].num = $(this).val();
                });
            })
            // 单个复选框的事件
            this.cont.on("input",".check",function(eve){
                // 根据选中状态，设置自定义属性，用来判断是否是全选
                if(this.checked){
                    $(this).attr("a","1");
                }else{
                    $(this).removeAttr("a");
                }

                // 找到所有复选框，判断全部状态，决定是否选中全选
                that.allCheck();

                // 获取id
                that.id = $(this).parent().parent().attr("data-id");

                // 将单个复选框的状态存到数据中
                that.setData((i)=>{
                    that.proMsg[i].check = this.checked;
                });
            })
            // 全选复选框的事件
            $(".allCheck").on("click",function(){
                let chk = Array.from($(".check"))
                // 遍历所有复选框
                chk.forEach(val=>{
                    // 设置所有复选框的状态
                    val.checked = this.checked;

                    // 修改自定义属性，用来判断是否是全选
                    if(this.checked){
                        $(val).attr("a",1);
                    }else{
                        $(val).removeAttr("a");
                    }

                    // 逐个获取单个复选框的id
                    that.id = $(val).parent().parent().attr("data-id");
                    // 逐个修改单个复选框的数据中的状态
                    that.setData((i)=>{
                        that.proMsg[i].check = this.checked;
                    });
                })
            })
        }
        setPrice(){
            // 计算总数量
            // console.log(that.proMsg)
            let sum = 0;
            this.proMsg.forEach(val=>{
                if(val.check){
                    sum += parseInt(val.num);
                }
            })
            $(".allNum").html(sum);

            // 计算总价
            let sumPrice = 0;
            this.proMsg.forEach(val=>{
                if(val.check){
                    sumPrice += parseInt(val.num) * parseFloat(val.price);
                }
            })
            $(".allPrice").html(sumPrice);

        }
        allCheck(){
            // 找到所有复选框，判断全部状态，决定是否选中全选
            let chk = Array.from($(".check"));
            const onoff = chk.every(val=>{
                return $(val).attr("a") == 1
            })
            $(".allCheck").get(0).checked = onoff;
        }
        setData(cb){
            let i=0;
            this.proMsg.some((val,idx)=>{
                i = idx;
                return val.id === this.id;
            })
            cb(i);
            localStorage.setItem("proMsg",JSON.stringify(this.proMsg))

            this.setPrice();
        }
        load(){
            $.ajax({
                url:this.url,
                success:(res) => {
                    this.res = JSON.parse(res)
                    
                    this.getData();
                }
            })
        }
        getData(){
            this.proMsg = localStorage.getItem("proMsg") ? JSON.parse(localStorage.getItem("proMsg")) : [];
            this.render();
        }
        render(){
            let str = "";
            for(let i=0;i<this.res.length;i++){
                for(let j=0;j<this.proMsg.length;j++){
                    if(this.res[i].proId === this.proMsg[j].id){
                        str += `<tr data-id="${this.proMsg[j].id}">
                                    <td><input type="checkbox" class="check" ${this.proMsg[j].check ? 'checked' : ''} ${this.proMsg[j].check ? 'a=1' : ''}></td>
                                    <td><img src="${this.res[i].proImg}"></td>
                                    <td>${this.res[i].proName}</td>
                                    <td><input type="number" value="${this.proMsg[j].num}" class="set"></td>
                                    <td>${this.res[i].price}</td>
                                    <td>${this.res[i].price * this.proMsg[j].num}</td>
                                    <td><span class="btn btn-warning del">删除</span></td>
                                </tr>`
                    }
                }
            }
            this.cont.html(str);
            this.allCheck();
            this.setPrice();
        }
    }

    new Cart;

</script>
</html>